//
//  CZEmoticonlnputView.swift
//  新浪微博
//
//  Created by Jack.Lin on 16/7/18.
//  Copyright © 2016年 Jack.Lin. All rights reserved.
//

import UIKit

// 表情输入视图
class CZEmoticonInputView: UIView {

    private let cellId = "cellId"
    
    @IBOutlet weak var toolBar: UIView!
    @IBOutlet weak var collectionView: UICollectionView!
    
    // 选中表情回调闭包属性
    private var selectedEmoticonCallBack: ((emoticon: JKEmoticon?)->())?
    
    class func inputView(selectedEmoticon: (emoticon: JKEmoticon?)->()) -> CZEmoticonInputView {
        
        let nib = UINib(nibName: "CZEmoticonInputView", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! CZEmoticonInputView
        
        // 记录闭包
        v.selectedEmoticonCallBack = selectedEmoticon
        
        return v
    }

    override func awakeFromNib() {
        
        collectionView.backgroundColor = UIColor.white()
        
//        let nib = UINib(nibName: "CZEmoticonCell", bundle: nil)
        
//        collectionView.register(nib, forCellWithReuseIdentifier: cellId)
        collectionView.register(CZEmoticonCell.self, forCellWithReuseIdentifier: cellId)
    }

}

extension CZEmoticonInputView: UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return JKEmoticonManager.shared.packages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        return 8
        return JKEmoticonManager.shared.packages[section].numberOfpages
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CZEmoticonCell
        
//        cell.backgroundColor = UIColor.red()
//        cell.label.text = "\(indexPath.section) - \(indexPath.item)"
        cell.emoticons = JKEmoticonManager.shared.packages[indexPath.section].emoticon(page: indexPath.item)
        
        // 设置代理 - 不适合用闭包
        cell.delegate = self
        
        return cell
    }
}

// MARK: - CZEmoticonCellDelegate

extension CZEmoticonInputView: CZEmoticonCellDelegate {

    func emoticonCellDidSelectedEmoticon(cell: CZEmoticonCell, em: JKEmoticon?) {
//        print(em)
        
        // 执行闭包 , 回调选中的表情
        selectedEmoticonCallBack?(emoticon: em)
    }
}

